import configparser
import os
import pickle
import json
from concurrent.futures.process import ProcessPoolExecutor
from datetime import datetime
import time
import requests

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

from Logging import Logging
from util import parse_json

cfg = configparser.RawConfigParser()
conf_path = "./config.conf"
cfg.read([conf_path], encoding='utf-8')

WIDTH = 375
HEIGHT = 812
PIXEL_RATIO = 3.0
UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1'
User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/112.0'

logger = Logging(__name__).get_logger()

class PiaoXQ:
    def __init__(self):
        self.piao_url = "https://m.piaoxingqiu.com/"
        self.mine_url = "https://m.piaoxingqiu.com/mine"
        # 购票界面url
        self.book_url = cfg.get("ticket_info", "book_url").strip()
        # 浏览器驱动
        self.driver_path = cfg.get("other", "driver_path").strip()
        # 项目ID
        self.project_id = cfg.get("ticket_info", "project_id").strip()
        self.sessions = int(cfg.get("ticket_info", "sessions").strip())
        self.plans_list = cfg.get("ticket_info", "plans").strip().split(",")  # 抢票的价格挡位，从左向右
        self.plans = list(map(int, self.plans_list))

        self.num = int(cfg.get("ticket_info", "num").strip())
        self.session_sale_time = 0

        self.spider_session = SpiderSession()
        self.session = self.spider_session.get_session()
        # self.spider_session.load_cookies_from_local()

    def open_chrome(self):
        # 设置无头浏览器 无界面浏览器
        self.chrome_options = webdriver.ChromeOptions()
        # 设置默认编码为utf-8，也就是中文
        self.chrome_options.add_argument('lang=zh_CN.UTF-8')
        # 禁止硬件加速
        self.chrome_options.add_argument('--disable-gpu')
        # 取消沙盒模式
        self.chrome_options.add_argument('--no-sandbox')
        # 禁止弹窗广告
        self.chrome_options.add_argument('--disable-popup-blocking')
        # 去掉反扒标志
        self.chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 此方法针对V78版本及以上有效，同时可以解决部分网站白屏的问题。
        self.chrome_options.add_experimental_option('useAutomationExtension', False)
        # ##大量渲染时候写入/tmp而非/dev/shm
        self.chrome_options.add_argument("-–disable-dev-shm-usage")
        desired_capabilities = DesiredCapabilities.CHROME
        desired_capabilities["pageLoadStrategy"] = "none"
        # # 忽略证书错误（实操没卵用）
        # self.chrome_options.add_argument('--ignore-certificate-errors')

        # 保存浏览历史下次读取直接读取里面的内容
        # dir_path = os.getcwd()
        # self.chrome_options.add_argument(f'user-data-dir={dir_path}/userData')

        mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO},
                           "userAgent": UA}
        self.chrome_options.add_experimental_option("mobileEmulation", mobileEmulation)

        self.driver = webdriver.Chrome(executable_path=self.driver_path, chrome_options=self.chrome_options)  # 此项稳定版打开
        # self.driver = webdriver.Chrome(executable_path=self.driver_path)  # 默认谷歌浏览器, 指定下驱动的位置
        # self.driver = webdriver.Chrome()  # 默认谷歌浏览器
        with open('./stealth.min.js') as f:
            js = f.read()
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": js
        })
        # 将window.navigator.webdriver属性变为undefined 防止检测
        # 修改get方法
        script = 'Object.defineProperty(navigator, "webdriver", {get:()=>undefined,});'
        # execute_cdp_cmd用来执行chrome开发这个工具命令
        self.driver.execute_script(script)

        self.driver.set_window_size(400, 900)

    def check_cookie(self):
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/user/buyer/v3/profile?src=WEB&channelId=&terminalSrc=WEB'
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id
        }
        resp = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        if resp_json['statusCode'] != 200:
            return True
        else:
            self.user_info = resp_json['data']
            '''
            "data": {
                        "bizUserId": "645a91d6c547ce00018f4546",
                        "bizCode": "FHL_M",
                        "subBizCode": "6267a80eed218542786f1494",
                        "gender": "",
                        "userLevel": 0,
                        "joinedDay": 3,
                        "cellphone": "182****5616"
                    }
            '''
            return False

    def login(self):
        if not os.path.exists('cookies.pkl'):  # 如果不存在cookie.pkl,就登录获取一下
            self.get_cookie()
        else:  # 存在就设置下cookie
            self.set_cookie()


    def get_cookie(self):
        self.open_chrome()
        self.driver.get(self.mine_url)
        user_info_div = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'user-info')))
        try:
            unlogin = user_info_div.find_element(By.CLASS_NAME, "unlogin")
            unlogin.click()
            while True:
                try:
                    register = self.driver.find_element(By.CLASS_NAME, "account-register-layout")
                    pass
                except Exception as ex:
                    try:
                        is_login = user_info_div.find_element(By.CLASS_NAME, "unlogin")
                    except Exception as ex1:
                        break
                    self.login()
                    pass
        except Exception as e:
            logger.info("------已登录------")
        logger.info("------已登录------")
        pickle.dump(self.driver.get_cookies(), open("cookies.pkl", "wb"))
        self.set_cookie()
        self.driver.quit()

    def set_cookie(self):
        try:
            cookies = pickle.load(open("cookies.pkl", "rb"))  # 载入cookie
            for cookie in cookies:
                if cookie.get('name') == 'consistent_code':
                    self.access_token = cookie.get('value')
            logger.info('------载入Cookie------')
        except Exception as e:
            logger.exception("------cookie 设置失败，原因：%s------" % e)

    def run(self):
        try:
            # 登录
            self.login()

            # 校验token
            if self.check_cookie():
                # token失效 重新登录
                self.get_cookie()

            start_time = time.time()
            logger.info("------准备抢票，时间点：%s------" % datetime.now())
            loop = 1
            while True:
                try:
                    logger.info("------正在进行第 %s 轮抢票------" % loop)
                    # 抢票
                    self.get_sessions()
                    break
                except Exception as ex:
                    if loop > self.num:
                        raise ex
                    loop += 1
                    pass

            end_time = time.time()
            logger.info("抢票结束，时间点：%s" % datetime.now())
            logger.info("抢票总时长：%s， 此时长不包括登录时间" % (end_time - start_time))
            logger.info("抢票成功，抓紧去订单中付款！！")
        except Exception as e:
            logger.exception("******抢票失败，原因：%s******" % e)
            time.sleep(600)
            # self.driver.quit()

    def get_sessions_static_data(self, index):
        """获取场次信息"""
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/v3/show/'+self.project_id+'/sessions_static_data'
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/'+self.project_id+'?from=content&isFree=false',
        }

        resp = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        params = {
            "_shows": None,
            "_sessions": None,
            "_combos": [],
        }
        if resp_json['statusCode'] != 200:
            logger.error("------获取场次信息异常------")
        else:
            resp_json_data = resp_json['data']
            _shows = [
                {
                    "showId": self.project_id,
                    "showName": resp_json_data['showName'],
                    "seatPickType": "SUPPORT_NONE"
                }
            ]
            params['_shows'] = _shows

            sessionVOs = resp_json_data['sessionVOs']
            sessionVO = sessionVOs[index]
            _sessions = [
                {
                    "bizShowSessionId": sessionVO['bizShowSessionId'],
                    "stdShowSessionId": sessionVO['stdShowSessionId'],
                    "sessionName": sessionVO['sessionName'],
                    "supportSeatPicking": False
                }
            ]
            params['_sessions'] = _sessions
        return params

    def get_sessions(self):
        """获取场次信息"""
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/v3/show/'+self.project_id+'/sessions_dynamic_data'
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/'+self.project_id+'?from=content&isFree=false',
        }

        resp = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        if resp_json['statusCode'] != 200:
            logger.error("------获取场次信息异常------")
            raise Exception(resp_json['comments'])
        else:
            resp_data = resp_json['data']
            sessions = resp_data['sessionVOs']

            i = self.sessions - 1
            session = sessions[i]
            params = self.get_sessions_static_data(i)
            session_status = session['sessionStatus']

            if session_status == 'PENDING':
                # session_sale_time_countdown = int(session['sessionSaleTimeCountdown'])
                # sleep_interval = session_sale_time_countdown/1000
                self.session_sale_time = int(session['sessionSaleTime'])
            self.get_seat_plans(session['bizShowSessionId'], params)

            # for i in range(len(sessions)):
            #     session = sessions[i]
            #     params = self.get_sessions_static_data(i)
            #     self.get_seat_plans(session['bizShowSessionId'], params)
            #     break

            # with ProcessPoolExecutor(len(sessions)) as pool:
            #     for i in range(len(sessions)):
            #         session = sessions[i]
            #         params = self.get_sessions_static_data(i-1)
            #         self.get_seat_plans(session['bizShowSessionId'], params)

    def getSessionStatus(self):
        """获取场次信息"""
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/v3/show/' + self.project_id + '/sessions_dynamic_data'
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id + '?from=content&isFree=false',
        }
        resp = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        if resp_json['statusCode'] != 200:
            logger.error("------获取场次信息异常------")
            raise Exception(resp_json['comments'])
        else:
            resp_data = resp_json['data']
            sessions = resp_data['sessionVOs']
            i = self.sessions - 1
            session = sessions[i]
            session_status = session['sessionStatus']
            return session_status

    def get_seat_plans_static_data(self, session_id, index):
        # 获取余票
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/v3/show/'+self.project_id+'/show_session/'+session_id+'/seat_plans_static_data'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id + '?from=content&isFree=false',
        }
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        resp_static = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp_static.text)
        resp_json_static = parse_json(resp_static.text)
        params = {
            "_seatPlans": None,
            "tickets": None,
            "operations": None,
            "productSKUs": []
        }
        if resp_json_static['statusCode'] != 200:
            logger.error("------获取余票信息异常------")
        else:
            resp_static_data = resp_json_static['data']
            seat_plans = resp_static_data['seatPlans']
            planVO = seat_plans[index]
            logger.info("----------选票成功：%s 票价：%s----------" % (planVO['seatPlanName'], planVO['originalPrice']))
            _seatPlans = [
                {
                    "seatPlanId": planVO['seatPlanId'],
                    "seatPlanName": planVO['seatPlanName'],
                    "stdSeatPlanId": planVO['stdSeatPlanId'],
                    "originalPrice": int(planVO['originalPrice'])
                }
            ]
            params['_seatPlans'] = _seatPlans

            generateId1 = str(round(time.time() * 1000)) + "100000004"
            generateId2 = str(round(time.time() * 1000)) + "100000009"
            tickets = [
                {
                    "generateId": generateId1,
                    "seatPlanId": planVO['seatPlanId'],
                    "show": {
                        "showId": self.project_id
                    },
                    "session": {
                        "bizShowSessionId": session_id
                    }
                },
                {
                    "generateId": generateId2,
                    "seatPlanId": planVO['seatPlanId'],
                    "show": {
                        "showId": self.project_id
                    },
                    "session": {
                        "bizShowSessionId": session_id
                    }
                }
            ]
            params['tickets'] = tickets

            operationId1 = str(round(time.time() * 1000)) + "100000005"
            operationId2 = str(round(time.time() * 1000)) + "100000010"
            operations = [
                {
                    "id": operationId1,
                    "ticketGenerateId": generateId1,
                    "snapshotId": None
                },
                {
                    "id": operationId2,
                    "ticketGenerateId": generateId2,
                    "snapshotId": None
                }
            ]
            params['operations'] = operations
        return params

    def get_seat_plans(self, session_id, params):
        logger.info("**********开始抢票: %s **********" % datetime.now())
        # 获取余票
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/v3/show/'+self.project_id+'/show_session/'+session_id+'/seat_plans_dynamic_data'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id + '?from=content&isFree=false',
        }
        payload = {
            'src': 'WEB',
            'channelId': '',
            'terminalSrc': 'WEB'
        }
        resp_dynamic = self.session.get(url=url, params=payload, headers=headers)
        logger.info(resp_dynamic.text)
        resp_json_dynamic = parse_json(resp_dynamic.text)
        if resp_json_dynamic['statusCode'] != 200:
            logger.error("------获取余票信息异常------")
        else:
            resp_dynamic_data = resp_json_dynamic['data']
            seat_plans = resp_dynamic_data['seatPlans']
            seat_plan_ids = []
            purchaseSeatPlanLimiters = []
            for i in range(len(seat_plans)):
                plan = seat_plans[i]
                seat_plan_ids.append(plan['seatPlanId'])
                limitation = 6
                purchaseSeatPlanLimiters.append({
                    "id": plan['seatPlanId'],
                    "type": "purchaseSeatPlanLimiter",
                    "limitation": limitation,
                    "limiterId": plan['seatPlanId']
                })

            for i in self.plans:
                plan = seat_plans[i-1]
                if int(plan['canBuyCount']) > 2:
                    params1 = self.get_seat_plans_static_data(session_id, (i-1))
                    seat_plan_id = plan['seatPlanId']
                    filters_params = self.get_filters_data(session_id, seat_plan_ids, purchaseSeatPlanLimiters)
                    self.get_generate_code_params(session_id, seat_plan_id, params, params1, filters_params)
                    break

    def get_filters_data(self, session_id, seat_plan_ids, purchaseSeatPlanLimiters):
        url1 = 'https://m.piaoxingqiu.com/cyy_gatewayapi/show/pub/risk/v3/limit?channelId=&terminalSrc=WEB'
        payload = {
            "showId": self.project_id,
            "sessionId": session_id,
            "seatPlanIds": seat_plan_ids,
            "priorityParam": {},
            "src": "WEB"
        }
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id + '?from=content&isFree=false',
        }
        resp = self.session.post(url=url1, json=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        filters = []
        if resp_json['statusCode'] != 200:
            logger.error("------获取项目状态异常------")
        else:
            resp_data = resp_json['data']
            showAvailableQuantityVO = resp_data['showAvailableQuantityVOS'][0]
            sessionAvailableQuantityVO = resp_data['sessionAvailableQuantityVOS'][0]
            filters.append({
                "id": showAvailableQuantityVO['showId'],
                "type": "purchaseShowLimiter",
                "limitation": int(showAvailableQuantityVO['availableQuantity']),
                "limiterId": showAvailableQuantityVO['showId']
            })
            filters.append({
                "id": sessionAvailableQuantityVO['sessionId'],
                "type": "purchaseSessionLimiter",
                "limitation": int(sessionAvailableQuantityVO['availableQuantity']),
                "limiterId": sessionAvailableQuantityVO['sessionId']
            })
        new_filters = filters + purchaseSeatPlanLimiters
        return new_filters


    def get_generate_code_params(self, session_id, plan_id, params1, params2, filters_params):
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/home/pub/v3/wxapps/short_codes/generate_code?channelId=&terminalSrc=WEB'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/booking/' + self.project_id + '?from=content&isFree=false',
        }
        payload = {
            "scene": {
                "bizShowSessionId": session_id,
                "seatPlanId": plan_id,
                "hasChannelDiscount": None,
                "checkChannelFreeCombo": None,
                "sameSessionPromotions": None,
                "saleAssistantJson": {
                    "deliverFee": -1,
                    "deliverPriceItemId": "",
                    "shoppingCart": {
                        "isOpen": True,
                        "currentSnapshotId": None,
                        "_shows": params1['_shows'],
                        "_sessions": params1['_sessions'],
                        "_combos": params1['_combos'],
                        "_seatPlans": params2['_seatPlans'],
                        "tickets": params2['tickets'],
                        "operations": params2['operations'],
                        "productSKUs": params2['productSKUs'],
                    },
                    "selectedShow": params1['_shows'],
                    "selectedSession": params1['_sessions'],
                    "discounts": [
                        {
                            "id": "comboDiscount",
                            "level": 1,
                            "type": "comboDiscount"
                        }
                    ],
                    "filters": filters_params
                }
            },
            "bizCode": self.user_info['bizCode'],
            "src": "WEB"
        }

        self.countdown = (self.session_sale_time - round(time.time() * 1000)) - 1000
        if self.countdown > 0:
            logger.info("**********等待抢票时间：%s 秒**********" % (self.countdown / 1000))
            time.sleep(self.countdown / 1000)

        while True:
            session_status = self.getSessionStatus()
            if session_status == 'PENDING':
                continue
            else:
                break

        resp = self.session.post(url=url, json=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        if resp_json['statusCode'] != 200:
            logger.error("------生成订单异常------")
        else:
            resp_data = resp_json['data']
            wxa_code = resp_data['wxaCode']
            logger.info("----------生成订单成功: %s ----------" % wxa_code)
            self.create_order(wxa_code, session_id, plan_id, params2['_seatPlans'][0]['originalPrice'])

    def create_order(self, cpId, session_id, plan_id, original_price):
        audiences = self.get_user_audiences(cpId, session_id)
        address_param = self.get_address_param(cpId)
        pre_order = self.get_pre_order(cpId, session_id, plan_id, original_price, address_param['addressParam']['addressId'])

        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/trade/buyer/order/v3/create_order'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/order/confirm?cpId=' + cpId,
        }
        payload = {
            "audienceIds": audiences['audienceIds'],
            "addressParam": address_param['addressParam'],
            "contactParam": address_param['contactParam'],
            "locationParam": address_param['locationParam'],
            "paymentParam": pre_order['paymentParam'],
            "priceItemParam": pre_order['priceItemParam'],
            "items": pre_order['items'],
            "many2OneAudience": audiences['many2OneAudience'],
            "one2oneAudiences": audiences['one2oneAudiences'],
            "src": "WEB"
        }

        logger.info("**********创建订单，入参: %s **********" % str(payload))
        logger.info("**********创建订单时间点: %s **********" % datetime.now())
        while True:
            resp = self.session.post(url=url, json=payload, headers=headers)
            logger.info(resp.text)
            resp_json = parse_json(resp.text)
            if resp_json['statusCode'] != 200:
                logger.error(resp_json['comments'])
                if resp_json['comments'] == '该演出还未开售':
                    continue
                else:
                    raise Exception("抢票失败: %s" % resp_json['comments'])
            else:
                resp_data = resp_json['data']
                logger.info("**********抢票成功，请前往APP抓紧时间付款**********")
                break

    def get_user_audiences(self, cpId, session_id):
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/user/buyer/v3/user_audiences?src=WEB&channelId=&terminalSrc=WEB&offset=0&length=50&bizCode=FHL_M&idTypes=ID_CARD,PASSPORT,MAINLAND_TRAVEL_PERMIT_TAIWAN,MAINLAND_TRAVEL_PERMIT_HK_MC&showId='
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/order/confirm?cpId=' + cpId,
        }
        resp = self.session.get(url=url, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        resp_data = resp_json['data']
        data1 = resp_data[0]
        data2 = resp_data[1]
        params = {
            'audienceIds': [resp_data[0]['id'], resp_data[1]['id']],
            'many2OneAudience': {},
            "one2oneAudiences": [
                {
                    "audienceId": resp_data[0]['id'],
                    "sessionId": session_id
                },
                {
                    "audienceId": resp_data[1]['id'],
                    "sessionId": session_id
                }
            ]
        }
        return params

    def get_address_param(self, cpId):
        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/user/buyer/v3/user/addresses/default?showId=&src=WEB&channelId=&terminalSrc=WEB'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/order/confirm?cpId=' + cpId,
        }
        resp = self.session.get(url=url, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        resp_data = resp_json['data']

        addressParam = {
            "address": resp_data['detailAddress'],
            "addressId": resp_data['addressId'],
            "district": "06",
            "city": "01",
            "province": "11"
        }
        contactParam = {
            "cellphone": resp_data['username'],
            "receiver": resp_data['cellphone']
        }
        locationParam = {
            "locationCityId": "1101"
        }

        return {
            'addressParam': addressParam,
            'contactParam': contactParam,
            'locationParam': locationParam
        }

    def get_pre_order(self, cpId, session_id, plan_id, ticket_price, address_id):
        items = [
            {
                "skus": [
                    {
                        "seatPlanId": plan_id,
                        "sessionId": session_id,
                        "showId": self.project_id,
                        "skuId": plan_id,
                        "skuType": "SINGLE",
                        "ticketPrice": ticket_price,
                        "qty": 2,
                        "deliverMethod": "EXPRESS"
                    }
                ],
                "spu": {
                    "id": self.project_id,
                    "spuType": "SINGLE"
                }
            }
        ]

        url = 'https://m.piaoxingqiu.com/cyy_gatewayapi/trade/buyer/order/v3/pre_order?channelId=&terminalSrc=WEB'
        url1 = 'https://m.piaoxingqiu.com/cyy_gatewayapi/trade/buyer/order/v3/price_items?channelId=&terminalSrc=WEB'
        headers = {
            'access-token': self.access_token,
            'Referer': 'https://m.piaoxingqiu.com/order/confirm?cpId=' + cpId,
        }
        payload = {
            'items': items,
            'src': 'WEB'
        }
        payload1 = {
            'addressId': address_id,
            'locationCityId': '110106',
            'items': items,
            'src': 'WEB'
        }
        resp = self.session.post(url=url, json=payload, headers=headers)
        logger.info(resp.text)
        resp_json = parse_json(resp.text)
        resp_data = resp_json['data']

        resp1 = self.session.post(url=url1, json=payload1, headers=headers)
        logger.info(resp1.text)
        resp_json1 = parse_json(resp1.text)
        resp_data1 = resp_json1['data'][0]

        price_items = resp_data['priceItems']
        priceItemParam = [
            {
                "applyTickets": [],
                "priceItemName": price_items[0]['priceItemName'],
                "priceItemVal":  int(price_items[0]['priceItemVal']),
                "priceItemType": price_items[0]['priceItemType'],
                "priceItemSpecies": price_items[0]['priceItemSpecies'],
                "direction": price_items[0]['direction'],
                "priceDisplay": "￥" + str(int(price_items[0]['priceItemVal']))
            },
            {
                "applyTickets": [],
                "priceItemName": resp_data1['priceItemName'],
                "priceItemVal": int(resp_data1['priceItemVal']),
                "priceItemId": resp_data1['priceItemId'],
                "priceItemSpecies": resp_data1['priceItemSpecies'],
                "priceItemType": resp_data1['priceItemType'],
                "direction": resp_data1['direction'],
                "priceDisplay": "￥" + str(int(resp_data1['priceItemVal']))
            }
        ]

        amount = int(price_items[0]['priceItemVal']) + int(resp_data1['priceItemVal'])
        paymentParam = {
            "totalAmount": "%.2f" % amount,
            "payAmount": "%.2f" % amount
        }

        return {
            "paymentParam": paymentParam,
            "priceItemParam": priceItemParam,
            "items": items
        }

class SpiderSession:
    """
    Session相关操作
    """
    def __init__(self):
        self.cookies_dir_path = "./cookies/"

        self.session = self._init_session()

    def _init_session(self):
        session = requests.session()
        session.headers = self.get_headers()
        return session

    def get_headers(self):
        return {"User-Agent": User_Agent,
                "Accept": "application/json, text/plain, */*",
                "Host": "m.piaoxingqiu.com",
                "Connection": "keep-alive",
                "terminal-src": "WEB",
                "channel-id": "",
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/json;charset=UTF-8"}

    def get_user_agent(self):
        return User_Agent

    def get_session(self):
        """
        获取当前Session
        :return:
        """
        return self.session

    def get_cookies(self):
        """
        获取当前Cookies
        :return:
        """
        return self.get_session().cookies

    def set_cookies(self, cookies):
        self.session.cookies.update(cookies)

    def load_cookies_from_local(self):
        """
        从本地加载Cookie
        :return:
        """
        cookies_file = ''
        if not os.path.exists(self.cookies_dir_path):
            return False
        for name in os.listdir(self.cookies_dir_path):
            if name.endswith(".cookies"):
                cookies_file = '{}{}'.format(self.cookies_dir_path, name)
                break
        if cookies_file == '':
            return False
        with open(cookies_file, 'rb') as f:
            local_cookies = pickle.load(f)
        self.set_cookies(local_cookies)

    def save_cookies_to_local(self, cookie_file_name):
        """
        保存Cookie到本地
        :param cookie_file_name: 存放Cookie的文件名称
        :return:
        """
        cookies_file = '{}{}.cookies'.format(self.cookies_dir_path, cookie_file_name)
        directory = os.path.dirname(cookies_file)
        if not os.path.exists(directory):
            os.makedirs(directory)
        with open(cookies_file, 'wb') as f:
            pickle.dump(self.get_cookies(), f)

if __name__ == '__main__':
    piao = PiaoXQ()
    piao.run()